﻿package net.hcpme.service;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.nio.channels.SocketChannel;
import java.util.Date;

import net.hcpme.activity.Login;
import net.hcpme.dao.Message;
import net.hcpme.dao.MessageDao;
import net.hcpme.fragment.TacticsFragment;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;

public class ReceiveMessageService extends Service {

    private DatagramSocket ds = null;
    private DatagramPacket sendDp = null, receiveDp = null;
    private SocketChannel client = null;
    private InetSocketAddress isa = null;

    private MessageDao messageDao;

    private OnMessageListen onMessageListen;

    public interface OnMessageListen {
        public void messageResult(String message);
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        messageDao = new MessageDao(this);

        ConnectToServer();
        StartServerListener();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        final String message = intent.getStringExtra("message");
        new Thread(new Runnable() {
            @Override
            public void run() {
                SendMessageToServer(message);
            }
        }).start();
        return super.onStartCommand(intent, flags, startId);
    }

    // 用于链接服务器端
    private void ConnectToServer() {
        try {
            ds = new DatagramSocket(7000);
            isa = new InetSocketAddress(InetAddress.getByName("10.240.2.121"), 7000);
            client = SocketChannel.open();
            client.configureBlocking(false);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 向Server端发送消息
    public void SendMessageToServer(String msg) {
        try {
            byte[] buf = msg.getBytes("utf-8");
            int length = buf.length;
            sendDp = new DatagramPacket(buf, length, isa);
            ds.send(sendDp);
            Message message = new Message();
            message.setFrom("local");
            message.setMessage(msg);
            message.setDate(new Date().toString());
            message.setInOrOut(1);
            messageDao.installMessage(message);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void setOnMessageListen(OnMessageListen onMessageListen) {
        this.onMessageListen = onMessageListen;
    }

    // 启动服务器端的监听线程，从Server端接收消息
    private void StartServerListener() {
        ServerListener a = new ServerListener();
        a.start();
    }

    private class ServerListener extends Thread {
        @Override
        public void run() {
            // 无线循环，监听服务器,如果有不为空的信息送达，则更新Activity的UI
            while (true) {
                try {
                    byte[] data = new byte[1024];
                    // 创建接收方的套接字,并制定端口号和IP地址
                    receiveDp = new DatagramPacket(data, data.length);
                    ds.receive(receiveDp);
                    // 这里可以获得PC机上的IP，端口等信息。
                    Log.d("tag~~~", ">>>-------------IP: " + receiveDp.getSocketAddress());
                    // 输出内容： IP: 10.0.2.2/10.0.2.2:10000
                    Log.d("tag~~~", ">>>-data: " + new String(receiveDp.getData(), 0, receiveDp.getLength(), "utf-8"));
                    Intent intent = new Intent(Login.LOGIN_MESSAGE_RECEIVE_BROADCAST);
                    intent.putExtra("data", new String(receiveDp.getData(), 0, receiveDp.getLength(), "utf-8"));
                    sendBroadcast(intent);
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

}
